#include "ever17Util.h"

Ever17Util::Ever17Util(){
}

string Ever17Util::readExpr(fstream& buf) {
	int arg0 = buf.get()&0xFF;
	
	char op[1024];
	if (arg0 == 0xC0) {
		int mode = arg0;
		int val = buf.get() & 0xFF;
		sprintf(op,"VAR_%02x_%d", mode, val);
		return op;
	} else if (arg0 >= 0xC1 && arg0 <= 0xCF) {
		int mode = arg0;			
		short a ;
		short b ;
		buf.read((char*)&a,2);
		buf.read((char*)&b,2);
		sprintf(op,"VAR_%02x_%d_%d", mode, a, b);
		return op;
	} else if (arg0 >= 0xA0 && arg0 <= 0xAF) {
		int m = arg0;
		int a = buf.get() & 0xFF;
		int b = buf.get() & 0xFF;
		int nil = buf.get();
		if (nil != 0) 
			puts("I thought exprs ended with 0x00, but got: " + nil);

		if (b == 0 && nil == 0) {
			sprintf(op,"%d",256 * (m - 0xA0) + a);
			return op;
		} else if (m == 0xA4) {
			sprintf(op,"V_%02x",a);
			return op;
		}
		sprintf(op,"CONST_%02x_%02x_%02x", m, a, b);
		return op;
	} else if (arg0 >= 0x80 && arg0 <= 0x8F) {
		int a = arg0 - 0x80; //Constant
		int b = buf.get() & 0xFF;

		if (b != 0) {
			printf("I don't really know what to do with 2-byte constants: %02x %02x\n", arg0, b);
		
		}

		int nil = buf.get();
		if (nil != 0) {
			puts("I thought exprs ended with 0x00, but got: " + nil);
			
		}
		char digi[30];
		sprintf(digi,"%d",a);
		string dbg = digi;
		return dbg;
	} else if (arg0 == 0x28) {
		int arg1 = buf.get();
		if (arg1 != 0x0a) {
			puts("I thought 0x28 is always followed by 0x0a, but got: " + arg1);
		}
		return readExpr(buf);
	} else {
		puts("What kind of expr is this? " + arg0);
		char digi[30];
		sprintf(digi,"%d",arg0);
		string dbg = digi;
		return dbg;
	}
}


